helpers.js ➔ renameKey   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 2
nc 1
nop 3
1
/**
2
 * Clone an object,
3
 *
4
 * @param  {Mixed}  obj
5
 * @return {Object}
6
 */
7
export const clone = function(obj) {
8
    return typeof obj === 'object'
9
        ? JSON.parse(JSON.stringify(obj))
10
        : obj;
11
};
12
13
/**
14
 * Rename an object key.
15
 *
16
 * @param  {Object} object
17
 * @param  {String} oldName
18
 * @param  {String} newName
19
 * @return {Object}
20
 */
21
export const renameKey = function(object, oldName, newName) {
22
    if (typeof object !== 'object') {
23
        throw `Cannot rename property of a non-object, ${ typeof object } given`;
24
    }
25
26
    const newObject = clone(object);
27
    Object.defineProperty(newObject, newName, Object.getOwnPropertyDescriptor(newObject, oldName));
28
    delete newObject[oldName];
29
30
    return newObject;
31
};
32